package com.example.teacherservice.repository;

import com.example.teacherservice.entity.CouClass;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

public interface CouClassRepository extends JpaRepository<CouClass, Long> {

    // 方法1：使用JPA命名查询
    boolean existsByClassInfoIdAndCourseId(Long classId, Long courseId);

    // 方法2：自定义JPQL查询（备选方案）
    @Query("SELECT COUNT(c) > 0 FROM CouClass c WHERE c.classInfo.id = :classId AND c.course.id = :courseId")
    boolean existsClassCourseRelation(@Param("classId") Long classId, @Param("courseId") Long courseId);

    // 保留原有方法
    List<CouClass> findByClassId(Long classId);

    // 在CouClassRepository.java中添加
    @Query("SELECT COUNT(cc) FROM CouClass cc WHERE cc.classInfo.id = :classId")
    int countByClassInfoId(@Param("classId") Long classId);

    @Modifying
    @Query("DELETE FROM CouClass cc WHERE cc.classInfo.id = :classId")
    void deleteByClassInfoId(@Param("classId") Long classId);

    // 根据课程ID查询关联班级
    List<CouClass> findByCourseId(Long courseId);

    boolean existsByClassIdAndCourseId(Long classId, Long courseId);

    @Query("SELECT cc.courseId FROM CouClass cc WHERE cc.classId = :classId")
    List<Long> findCourseIdsByClassId(@Param("classId") Long classId);

    /**
     * 根据班级ID和课程ID删除关联记录
     * @param classId 班级ID
     * @param courseId 课程ID
     * @return 删除的记录数
     */
    @Modifying
    @Transactional
    @Query("DELETE FROM CouClass cc WHERE cc.classId = :classId AND cc.courseId = :courseId")
    int deleteByClassIdAndCourseId(@Param("classId") Long classId, @Param("courseId") Long courseId);

    // 使用JOIN FETCH优化查询
    @Query("SELECT cc FROM CouClass cc JOIN FETCH cc.course WHERE cc.classId = :classId")
    List<CouClass> findByClassIdWithCourse(@Param("classId") Long classId);

    @Modifying
    @Transactional
    @Query("DELETE FROM CouClass cc WHERE cc.courseId = :courseId")
    void deleteByCourseId(@Param("courseId") Long courseId);

}